import React, {useState, useEffect, useRef, useCallback} from 'react';
import {Text, View, StyleSheet, TouchableOpacity, FlatList, Image, Alert} from 'react-native';
import {useNavigation, useRoute} from '@react-navigation/native';
import screen from '../../utils/screen';
import Images from '../../images/images';
import LinkButton from '../../components/linkButton';
import {useLoading} from '../../components/loading/useLoading';
import {useToast} from '../../components/toast/useToast';
import {useModal} from '../../components/useModal';
import SearchDevice from './searchDevice';
import Container from '../../components/Container';
import BleUtil from '../../utils/bleUtil';
import TouchableView from '../../components/touchableView';
import {useAppStore} from '../../store/useAppStore';
import {BleState} from 'react-native-ble-manager';
import {isIos} from '../../utils/native';
import _ from 'lodash'
import {useDialog} from '../../components/dialog/useDialog';

const itemWidth = (screen.width - screen.PIXEL_60 ) /2

const AddDevice = ()=>{

    const navigation = useNavigation()
    const route = useRoute()
    const toast = useToast()
    const dialog = useDialog()
    const modal = useModal()
    const timerRef = useRef()
    const listRef = useRef([])

    const [list,setList] = useState([])
    const [refreshing, setRefreshing] = useState(false);
    const {appState:{bluetoothEnable,scanning,deviceList,currentDevice},updateAppState }= useAppStore()
    const [showList,setShowList] = useState(false)

    useEffect(()=>{
        navigation.setOptions({
            title:'添加设备'
        })

        const listener = BleUtil.addNewDeviceListener((data)=>{
            console.log('监听新设备',data);
            modal.close()

            timerRef.current && clearTimeout(timerRef.current)
            timerRef.current = setTimeout(()=>{
                addDevice(data)
                setShowList(true)
            },300)

        })

        const scanListener = BleUtil.addStopScanListener((data)=>{
            console.log('scan stop:',data)

            updateAppState({scanning: false})
            setRefreshing(false)
            setShowList(true)
            // setList(data)

        })


        BleUtil.getDiscoveredPeripherals((data)=>{
            console.log('发现的设备',data);
            // if(data.length){
            //     setShowList(true)
            //     listRef.current = data
            //     setList(listRef.current)
            // }
        })

        return ()=>{
            listener.remove();
            scanListener.remove()
            stopScan()
        }
    },[])

    const addDevice =(data)=>{
        if(listRef.current.length){
            let findIndex = listRef.current.findIndex(item=> item.id === data.id)
            if(findIndex === -1){
                listRef.current.unshift(data)
                console.log('newList,',listRef.current)
            }

        }else{
            listRef.current = [data]
        }
        setList(listRef.current)

    }




    const searchDevice = ()=> {

        if(!bluetoothEnable){
            toast.show('请打开蓝牙')
            return
        }

        BleUtil.checkState().then(state=>{
            console.log('check state',state);
            if(state === BleState.On){

            }
        })

        BleUtil.init().then(() => {
            // Success code
            console.log("Module initialized");

            scanDevices()
        }).catch(e=>{
            console.log('ble err:',e)
        });




    }

    const scanDevices = ()=>{
        if(isIos()){
            updateAppState({scanning: true})
            setRefreshing(true)
            BleUtil.scan().then(()=>{
                console.log('scan start')

            })
        }else{
            BleUtil.requestScanPermission().then(()=>{

                updateAppState({scanning: true})
                setRefreshing(true)
                BleUtil.enableBluetooth().then(() => {
                        // Success code
                        console.log("The bluetooth is already enabled or the user confirm");
                        BleUtil.scan().then(()=>{
                            console.log('scan start')

                        }).catch(error=>{
                            console.log('scan error',error);
                        })
                    }).catch((error) => {

                    });

            }).catch(err=>{

            })
        }

    }



    const stopScan = ()=>{
        // modal.close()

        BleUtil.stopScan().then(()=>{
            updateAppState({scanning: false})
        })
    }


    const listEmpty = (
        <View style={[styles.container,{height:400}]}>
            {/*<Image source={Images.loading} style={{width:screen.PIXEL_80,height:screen.PIXEL_80}}/>*/}
            <View style={{flexDirection:'row',alignItems:'center',marginTop:screen.PIXEL_30}}>
                <Text style={{fontSize:12,color:'#53687A'}}>未搜索到设备，下拉重试  </Text>
                <Image source={Images.refresh2} style={{width:screen.PIXEL_20,height:screen.PIXEL_20}}/>
            </View>
        </View>
    )

    const _keyExtractor = (item, index) => {
        console.log(`${item}${index}`);
        return `item_${index}`;
    }

    const onRefresh = ()=>{
        searchDevice()
        // BleUtil.getDiscoveredPeripherals(data=>{
        //     setRefreshing(false)
        //     setList(data)
        // })
    }

    const renderItem = ({item,index})=>{
        // console.log('render item:',item);
        let imageSource = Images.device02
        if(item.name.includes('TABE01')){
            imageSource = Images.device01
        }
        const isLeft = index % 2 === 0
        return (
            <TouchableView
                style={[styles.itemContainer,{
                    width:itemWidth,marginRight:isLeft ? screen.PIXEL_10 : 0,
                    marginLeft:isLeft ? 0 : screen.PIXEL_10
                }]}
                onPress={()=>{

                        if(currentDevice){
                            dialog.alertConfirm('继续添加将断开当前已连接设备',()=>{
                                BleUtil.disconnect(currentDevice.id).then(res=>{
                                    console.log('断开连接了：',res)
                                    updateAppState({currentDevice: null,battery:0})
                                    navigation.navigate('ConnectDevice',{data:item})
                                }).catch(error=>{
                                    updateAppState({currentDevice: null,battery:0})
                                    navigation.navigate('ConnectDevice',{data:item})
                                })
                            })

                        }else{
                            navigation.navigate('ConnectDevice',{data:item})
                        }

                }}
            >
                <Image source={imageSource} style={{width:screen.PIXEL_100,height:screen.PIXEL_100}} resizeMode={'contain'}/>
                <Text style={{fontSize:14,color:'#333',fontWeight:'500',marginTop:screen.PIXEL_30}}>{item.name}</Text>
            </TouchableView>
        )
    }
    return (
        <Container >

            {/*发现设备*/}
            {
                showList ? (
                    <FlatList
                        data={list}
                        contentContainerStyle={{paddingHorizontal:screen.PIXEL_20}}
                        keyExtractor={_keyExtractor}
                        renderItem={renderItem}
                        onRefresh={onRefresh}
                        numColumns={2}
                        refreshing={refreshing}
                        ListEmptyComponent={listEmpty}
                    />
                ) : (
                    <View style={styles.container}>
                        {
                            scanning ? (
                                <View style={styles.container}>
                                    <Image source={Images.searching} style={styles.imageStyle} resizeMode={'contain'}/>
                                    <Text style={{fontSize:17,color:'#333',marginTop:screen.PIXEL_50}}>搜索设备中...</Text>
                                </View>
                            ) : (
                                <LinkButton
                                    title={'添加设备'}
                                    onPress={()=>{
                                        BleUtil.checkState().then(state=>{
                                            console.log('蓝牙状态',state)
                                            if(state === BleState.Unauthorized){
                                                //未授权
                                                Alert.alert(
                                                    "温馨提示",
                                                    "因为您未设置同意使用蓝牙权限，暂不支持该功能，请前往系统开启设置",
                                                    [
                                                        {
                                                            text: "确定",
                                                            onPress: () => {

                                                            },
                                                            style: "cancel",
                                                        },
                                                    ],
                                                    {
                                                        cancelable: true,
                                                        onDismiss: () =>{

                                                        }

                                                    }
                                                );
                                            }else{
                                                searchDevice()
                                            }
                                        })
                                    }}
                                />
                            )
                        }

                    </View>

                )
            }



        </Container>
    )
}
export default AddDevice
const styles = StyleSheet.create({
    container:{
        flex: 1, justifyContent: 'center', alignItems: 'center'
    },
    itemContainer:{
        backgroundColor:'#fff',borderRadius:screen.PIXEL_20,marginTop:screen.PIXEL_30,
        justifyContent: 'center', alignItems: 'center',height:screen.PIXEL_320
    },
    imageStyle:{
        width:screen.scaleSize(600),height:screen.scaleSize(600)
    },
})
